package com.insurance.service.impl;

import java.util.List;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.insurance.bean.User;
import com.insurance.service.UserService;


@Transactional
public class UserServiceBean implements UserService {
	@Resource private SessionFactory sessionFactory;

	public void save(User user){
		sessionFactory.getCurrentSession().persist(user);
	}
	
	public void update(User user){
		sessionFactory.getCurrentSession().merge(user);
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public User getUser(Integer userid){
		return (User)sessionFactory.getCurrentSession().get(User.class, userid);
	}

	public void delete(Integer userid){
		sessionFactory.getCurrentSession().delete(
				sessionFactory.getCurrentSession().load(User.class, userid));
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@SuppressWarnings("unchecked")
	public List<User> getUsers(){		
		return sessionFactory.getCurrentSession().createQuery("from User").list();
	}
	
	public User verifyUser(User user) {
		String hql = "from User a where a.userName = ? and a.password = ?";
		try {
			@SuppressWarnings("rawtypes")
			List list = sessionFactory.getCurrentSession().createQuery(hql).
			setParameter(0, user.getUserName()).setParameter(1,user.getPassword()).list();
			if(list != null && list.size() > 0){
				return (User)list.get(0);
			} else{
				return null;
			}
			
		} catch(Exception e) {
			System.out.println(e.getMessage());
			return null;
		}
	}
}
